package com.geping.etl.common.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.geping.etl.common.entity.Sys_Department;
import com.geping.etl.common.entity.Sys_Subject;
import com.geping.etl.common.service.Sys_SubjectService;
import com.geping.etl.utils.EnvUitl;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.geping.etl.common.entity.Sys_Org;
import com.geping.etl.common.service.Sys_OrgService;

@RestController
public class Sys_OrgController {
	
	@Autowired
	private Sys_OrgService sys_OrgService;

	@Autowired
	private Sys_SubjectService sys_subjectService;
	
	//查询所有机构信息
	@RequestMapping(value="/sys_org",method=RequestMethod.GET)
	public ModelAndView getAllSys_org(){
		ModelAndView model = new ModelAndView();
		List<Sys_Org> list = sys_OrgService.findAllSysOrg();   //查询所有用户
		List<Sys_Subject> subjectList = sys_subjectService.findAllSubject().stream().filter(sys_subject -> sys_subject.getId() > 2).collect(Collectors.toList());
		Map<Integer, String> subjectMap = subjectList.stream().collect(Collectors.toMap(Sys_Subject::getId, Sys_Subject::getSubjectName, (k1, k2) -> k2));
		Map<String, Integer> subjectNameMap = subjectList.stream().collect(Collectors.toMap(Sys_Subject::getSubjectName,Sys_Subject::getId, (k1, k2) -> k2));
		model.addObject("subjectMap", subjectMap);
		model.addObject("subjectNameMap", subjectNameMap);
		model.addObject("subjectList", subjectList);
		model.addObject("list", list);
		model.addObject("systemNo", EnvUitl.props.getProperty("system.number"));
		model.setViewName("common/sys_org");
		return model;
	}
	
	
	//根据机构名称模糊查询机构信息
	@RequestMapping(value="/getSys_OrgByLikeOrgName",method=RequestMethod.GET)
	public ModelAndView getSys_OrgByLikeOrgName(HttpServletRequest request){
		ModelAndView model = new ModelAndView();
			try {
				String orgName = URLDecoder.decode(request.getParameter("orgName").replaceAll("%","%25"), "utf-8");
				if (orgName.contains("%")){
					orgName = orgName.replace("%","djskdffhdfka");
				}
				if (orgName.contains("_")){
					orgName = orgName.replace("_","djskdffhdfkb");
				}
				List<Sys_Org> list = new ArrayList<>();
				if(StringUtils.isNotBlank(orgName)) {
					list = sys_OrgService.getSys_UserByLikeOrgName(orgName);
				}else {
					list = sys_OrgService.findAllSysOrg();
				}
				if (orgName.contains("djskdffhdfka")){
					orgName = orgName.replace("djskdffhdfka","%");
				}
				if (orgName.contains("djskdffhdfkb")){
					orgName = orgName.replace("djskdffhdfkb","_");
				}
				model.addObject("list",list);
				model.addObject("orgName",orgName);
				model.setViewName("common/sys_org");
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return model;
	}
	
	
	//新增机构信息
	@RequestMapping(value="/addSys_Org",method=RequestMethod.POST)
	public void addSys_Org(HttpServletRequest request,HttpServletResponse response){
			String orgId_add = request.getParameter("orgId_add"); 
		    String orgName_add = request.getParameter("orgName_add");
		    String orgInsideCode_add = request.getParameter("orgInsideCode_add"); 
		    String licenseNumber_add = request.getParameter("licenseNumber_add"); 
		    String orgSortName_add = request.getParameter("orgSortName_add"); 
			String orgParentId_add = request.getParameter("orgParentId_add");
			String orgRegion_add = request.getParameter("orgRegion_add");
			String isBussiness_add = request.getParameter("isBussiness_add");
			String option_add = request.getParameter("option_add");
			String tel_add = request.getParameter("tel_add");
			String bankBankNumber = request.getParameter("bankBankNumber_add")==null?"":request.getParameter("bankBankNumber_add");

			String isHead_add;
	        if(request.getParameter("isHead_add").equals("是")){
	        	isHead_add = "Y";
	        }else{
	        	isHead_add = "N";
	        }
			String orgLevel_add = request.getParameter("orgLevel_add");
			PrintWriter out;
			if (orgId_add.length() > 50 || orgName_add.length() >255){
				try {
					out = response.getWriter();
					out.write("2");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else {
				List<Sys_Org> sysIsRepeatList = sysIsRepeatList = sys_OrgService.getOrgNameAndOrgId(orgName_add, orgId_add);
				try {
					out = response.getWriter();
					if(sysIsRepeatList.size() > 0){
						out.write("3");
						out.flush();
						out.close();
					}else{
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Sys_Org sys_org = new Sys_Org();
						sys_org.setOrgId(orgId_add);
						sys_org.setOrgName(orgName_add);
						sys_org.setOrgInsideCode(orgInsideCode_add);
						sys_org.setLicenseNumber(licenseNumber_add);
						sys_org.setOrgSortName(orgSortName_add);
						sys_org.setOrgParentId(orgParentId_add);
						sys_org.setOrgRegion(orgRegion_add);
						sys_org.setIsBussiness(isBussiness_add);
						sys_org.setIsHead(isHead_add);
						sys_org.setOrgLevel(orgLevel_add);
						sys_org.setCreateTime(sdf.format(new Date()));
						sys_org.setTel(tel_add);
						sys_org.setOption_(option_add);
						sys_org.setBankBankNumber(bankBankNumber);

						Sys_Org org = sys_OrgService.save(sys_org);
						try {
							out = response.getWriter();
							if(org != null){
								out.write("1");
							}else{
								out.write("0");
							}
							out.flush();
							out.close();
						}catch (IOException e) {
							e.printStackTrace();
						}
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	
	
	
	//修改机构
	@RequestMapping(value="/editSys_Org",method=RequestMethod.POST)
	public void editSys_Org(HttpServletRequest request,HttpServletResponse response){
				String editId = request.getParameter("editId");
				String orgId_edit = request.getParameter("orgId_edit"); 
			    String orgName_edit = request.getParameter("orgName_edit");
			    String orgInsideCode_edit = request.getParameter("orgInsideCode_edit"); 
			    String licenseNumber_edit = request.getParameter("licenseNumber_edit"); 
				String orgSortName_edit = request.getParameter("orgSortName_edit");
				String orgParentId_edit = request.getParameter("orgParentId_edit");
				String orgRegion_edit = request.getParameter("orgRegion_edit"); 
			    String isBussiness_edit = request.getParameter("isBussiness_edit"); 
				String isHead_edit;
				if(request.getParameter("isHead_edit").equals("是")){
					isHead_edit = "Y";
				}else{
					isHead_edit = "N";
				}
				String orgLevel_edit = request.getParameter("orgLevel_edit");
				String isEditOrgId = request.getParameter("isEditOrgId");
				String isEditOrgName = request.getParameter("isEditOrgName");
				String option_edit = request.getParameter("option_edit");
				String tel_edit = request.getParameter("tel_edit");
				String bankBankNumber = request.getParameter("bankBankNumber_edit")==null?"":request.getParameter("bankBankNumber_edit");
				
				String doFindOrgId = "";
				String doFindOrgName = "";
				PrintWriter out;
				if (orgId_edit.length() > 50 || orgName_edit.length() >255){
					try {
						out = response.getWriter();
						out.write("2");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}else {
					try {
						out = response.getWriter();
						if(isEditOrgId.equals("1") && isEditOrgName.equals("1")){   //用户同时修改了机构编号和机构名称
							doFindOrgId = orgId_edit;
							doFindOrgName = orgName_edit;
						}else if(isEditOrgId.equals("1") && isEditOrgName.equals("0")){  //用户只修改机构编号
							doFindOrgId = orgId_edit;
						}else if(isEditOrgId.equals("0") && isEditOrgName.equals("1")){  //只修改了机构名称
							doFindOrgName = orgName_edit;
						}else{

						}
						List<Sys_Org> isRepeatList = sys_OrgService.getOrgNameAndOrgId(doFindOrgName, doFindOrgId);  //通过机构编号和机构名称查询是否存在重名
						if(isRepeatList.size() > 0){
							out.write("3");
						}else{
							int result = sys_OrgService.updateSys_Org(Integer.valueOf(editId),orgId_edit,orgName_edit,orgSortName_edit,orgParentId_edit,orgRegion_edit,isBussiness_edit,isHead_edit,orgLevel_edit,orgInsideCode_edit,licenseNumber_edit,option_edit,tel_edit,bankBankNumber);
							if(result > 0){
								out.write("1");
							}else{
								out.write("0");
							}
						}
						out.flush();
						out.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}

	}

	
	
	
	//逻辑删除机构
	@RequestMapping(value="/deleteSys_Org",method=RequestMethod.POST)
	public void deleteSys_Org(HttpServletRequest request,HttpServletResponse response){
			String id = request.getParameter("id");
			String enabled = request.getParameter("enabled");
			int result = sys_OrgService.deleteSys_Org(Integer.valueOf(id),enabled);
			JSONObject permision = new JSONObject();
			PrintWriter out;
				try {
					out = response.getWriter();
					permision.put("result",result);
					out.print(permision.toString());
					out.flush();
					out.close();
				} catch (IOException e){
					e.printStackTrace();
				}
	}
	
	
	//Excel导出机构信息
	/*@RequestMapping(value="/exportExcelSys_Org",method=RequestMethod.GET)
	public void exportExcelSys_Org(HttpServletRequest request,HttpServletResponse response){
			//headers:excel中表列标题名
			String[] headers ={"ID","机构编号","机构名称","机构简称","上级机构编号","机构所属区域","机构层次","机构层级path","机构等级","机构地址","是否可用","是否顶级机构","电话","传真","电子邮件","是否业务机构","描述信息","开始日期","关闭日期","创建时间","排序","可选字段","主题代码"};  
			List<Sys_Org> list = sys_OrgService.findAllSysOrg();
			ExcelExportUtils<Sys_Org> eeu = new ExcelExportUtils<Sys_Org>();
			String fileName = "机构信息记录.xls";   //设置下载的文件名称
			String title = "机构信息记录";          //Excel表格sheet名称
			eeu.exportExcel(request,response,fileName,title,headers,list);
		}*/
}
